package com.yisu.auction.api.core.service.impl.func;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.*;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

public class JPushUtil {

	private static final Logger LOG = LoggerFactory.getLogger(JPushUtil.class);
	private static final String DEFAULT_APP_KEY = "b4a9fd93ff0dd65fbb0ab992";
	private static final String DEFAULT_MASTER_SECRET = "f5e46935efed0cd5bfa0a096";

	public static final String REGISTRATION_ID = "0900e8d85ef";
	public static final String TAG = "tag_api";

	/**
	 * 
	 * @Title: sendWinMsg @Description: 推送中奖消息给用户 @param memberId @param
	 * prizeId @param content @return void @throws
	 */
	public static void sendWinMsg(String appKey, String masterSecret, Long memberId, Long prizeId,Integer term, String content) {
		try{
			PushPayload payload = buildPushWinMsg(memberId,prizeId,term,content);
			payload.resetOptionsApnsProduction(true);
			pushMsg(appKey, masterSecret, payload);
		}catch(Exception e){
			LOG.error("sendWinMsg",e);
		}
		
	}

	public static void sendCommonMsg(String appKey, String masterSecret, Long memberId, String content) {
		try{
			PushPayload payload = buildCommonMsg(memberId, content);
			payload.resetOptionsApnsProduction(true);
			pushMsg(appKey, masterSecret, payload);
		}catch(Exception e) {
			LOG.error("send common message, root cause {}", e);
		}
	}
	
	public static void pushMsg(String appKey, String masterSecret, PushPayload payload){
		try {
			JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);
			PushResult result = jpushClient.sendPush(payload);
		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
		}
	}

	/**
	 * 
	 * @Title: sendNoticeMsg @Description: 发送系统通知 @return void @throws
	 */
	public static void sendNoticeMsg(String appKey, String masterSecret, String content) {
		try{
			PushPayload payload = buildPushObject_all_all_alert(content);
			payload.resetOptionsApnsProduction(true);
			pushMsg(appKey, masterSecret, payload);
		}catch(Exception e){
			LOG.error("sendWinMsg",e);
		}
	}

	public static PushPayload buildPushWinMsg(Long memberId, Long prizeId,Integer term, String content) {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.tag(memberId.toString()))
				.setNotification(Notification.newBuilder().setAlert(content)
						.addPlatformNotification(AndroidNotification.newBuilder().setTitle("中奖消息").addExtra("prizeId", prizeId).addExtra("term", term).addExtra("name", content).build())
						.addPlatformNotification(
								IosNotification.newBuilder().incrBadge(1).setSound("win.wav").addExtra("prizeId", prizeId).addExtra("term", term).addExtra("name", content).build())
						.build())
				.build();
	}
	
	public static PushPayload buildPushMsg(Long memberId, String content) {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.tag(memberId.toString()))
				.setNotification(Notification.newBuilder().setAlert(content)
						.addPlatformNotification(AndroidNotification.newBuilder().setTitle("").addExtra("prizeId", "").addExtra("term", "").addExtra("name", "").build())
						.addPlatformNotification(
								IosNotification.newBuilder().addExtra("prizeId", "").addExtra("term", "").addExtra("name", "").build())
						.build())
				.build();
	}

	public static PushPayload buildCommonMsg(Long memberId, String content) {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.tag(memberId.toString()))
				.setNotification(Notification.newBuilder().setAlert(content)
						.addPlatformNotification(AndroidNotification.newBuilder().build())
						.addPlatformNotification(IosNotification.newBuilder().build())
						.build())
				.build();
	}

	public static void testSendPush(String appKey, String masterSecret, String content) {
		JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);
		// For push, all you need do is to build PushPayload object.
		PushPayload payload = buildPushObject_all_all_alert(content);
		payload.resetOptionsApnsProduction(true);
		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("Got result - " + result);
			System.out.println(result);

		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);

		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
		}
	}

	public static PushPayload buildPushObject_all_all_alert(String content) {
		return PushPayload.alertAll(content);
	}

	public static PushPayload buildPushObject_all_alias_alert(String content) {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias("alias1"))
				.setNotification(Notification.alert(content)).build();
	}

	public static PushPayload buildPushObject_android_tag_alertWithTitle(String content, String title) {
		return PushPayload.newBuilder().setPlatform(Platform.android()).setAudience(Audience.tag("tag1"))
				.setNotification(Notification.android(content, title, null)).build();
	}

	public static PushPayload buildPushObject_android_and_ios() {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.tag("111"))
				.setNotification(Notification.newBuilder().setAlert("alert content")
						.addPlatformNotification(AndroidNotification.newBuilder().setTitle("Android Title").build())
						.addPlatformNotification(
								IosNotification.newBuilder().incrBadge(1).addExtra("extra_key", "extra_value").build())
						.build())
				.build();
	}

	public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String alert, String content) {
		return PushPayload.newBuilder().setPlatform(Platform.ios()).setAudience(Audience.tag_and("tag1", "tag_all"))
				.setNotification(Notification.newBuilder()
						.addPlatformNotification(IosNotification.newBuilder().setAlert(alert).setBadge(5)
								.setSound("happy").addExtra("from", "JPush").build())
						.build())
				.setMessage(Message.content(content)).setOptions(Options.newBuilder().setApnsProduction(true).build())
				.build();
	}

	public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(String content) {
		return PushPayload.newBuilder().setPlatform(Platform.android_ios())
				.setAudience(Audience.newBuilder().addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
						.addAudienceTarget(AudienceTarget.alias("alias1", "alias2")).build())
				.setMessage(Message.newBuilder().setMsgContent(content).addExtra("from", "JPush").build()).build();
	}

	public static void testSendPushWithCustomConfig(String appKey, String masterSecret, String content) {
		ClientConfig config = ClientConfig.getInstance();
		// Setup the custom hostname
		config.setPushHostName("https://api.jpush.cn");

		JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3, null, config);

		// For push, all you need do is to build PushPayload object.
		PushPayload payload = buildPushObject_all_all_alert(content);

		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("Got result - " + result);

		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);

		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
		}
	}

	public static void testSendIosAlert(String appKey, String masterSecret) {
		JPushClient jpushClient = new JPushClient(masterSecret, appKey);

		IosAlert alert = IosAlert.newBuilder().setTitleAndBody("test alert", "test ios alert json")
				.setActionLocKey("PLAY").build();
		try {
			PushResult result = jpushClient.sendIosNotificationWithAlias(alert, new HashMap<String, String>(),
					"alias1");
			LOG.info("Got result - " + result);
		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
		}
	}

	public static void testSendWithSMS(String appKey, String masterSecret) {
		JPushClient jpushClient = new JPushClient(masterSecret, appKey);
		try {
			SMS sms = SMS.content("Test SMS", 10);
			PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
			LOG.info("Got result - " + result);
		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
		}
	}

	public static void main(String[] args) {
		// testSendPushWithCustomConfig();
		// testSendIosAlert();
		// testSendPush();
//		JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);
//		PushPayload payload = buildPushObject_android_and_ios();
//		try {
//			PushResult result = jpushClient.sendPush(payload);
//			LOG.info("Got result - " + result);
//
//		} catch (APIConnectionException e) {
//			LOG.error("Connection error. Should retry later. ", e);
//
//		} catch (APIRequestException e) {
//			LOG.error("Error response from JPush server. Should review and fix it. ", e);
//			LOG.info("HTTP Status: " + e.getStatus());
//			LOG.info("Error Code: " + e.getErrorCode());
//			LOG.info("Error Message: " + e.getErrorMessage());
//			LOG.info("Msg ID: " + e.getMsgId());
//		}
		sendCommonMsg(DEFAULT_APP_KEY, DEFAULT_MASTER_SECRET, 10010061l,"恭喜您！获得了66元新人大礼包，请在我的红包中查看！");
		String content = "你是随机调查的幸运者。接受微信满意度调查后，你可以得到30到50元的奖励，官方微信ximenayong";
		PushPayload payload = buildPushMsg(10010061l,content);
		payload.resetOptionsApnsProduction(true);
//		content = "你是随机调查的幸运者。接受微信满意度调查后，你可以得到30到50元的奖励，官方微信ximenayong";//MessageFormat.format(content,"xxx" ,"三只松鼠 夏威夷果 澳洲坚果特产 奶油味");
//		PushPayload payload =  buildPushWinMsg(10001099l,38l,10,"三只松鼠 夏威夷果 澳洲坚果特产 奶油味");
		pushMsg("a797bf9f9e23b9035332b31a", "b77f62ccbaa15dc5cb9255c1", payload);
		
//		sendNoticeMsg("系统通知测试");
//		testSendPush("系统通知测试");
	}

}
